package com.example.controller;

import com.example.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String password = credentials.get("password");

        // 实际项目中应验证用户名密码
        if ("admin".equals(username) && "password".equals(password)) {
            String token = jwtUtil.generateToken(username, "ADMIN");

            // 创建更完整的响应
            Map<String, Object> response = new HashMap<>();
            response.put("token_type", "Bearer");
            response.put("access_token", token);
            response.put("expires_in", jwtUtil.getExpiration() / 1000);  // 秒
            response.put("user_id", username);
            response.put("role", "ADMIN");

            // 添加刷新令牌（可选）
            String refreshToken = jwtUtil.generateRefreshToken(username);
            response.put("refresh_token", refreshToken);
            response.put("refresh_expires_in", 604800);  // 7天（秒）

            return ResponseEntity.ok(response);
        }
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("error", "invalid_credentials");
        errorResponse.put("message", "Invalid username or password");
        return ResponseEntity.status(401).body(errorResponse);
    }
    // 添加刷新令牌接口
    @PostMapping("/refresh")
    public ResponseEntity<?> refreshToken(@RequestParam("refresh_token") String refreshToken) {
        try {
            Claims claims = jwtUtil.getClaimsFromToken(refreshToken);
            String tokenType = claims.get("type", String.class);

            if (!"refresh".equals(tokenType)) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "invalid_token_type");
                return ResponseEntity.status(400).body(errorResponse);
            }

            String username = claims.getSubject();
            String newAccessToken = jwtUtil.generateToken(username, "ADMIN");

            Map<String, Object> response = new HashMap<>();
            response.put("access_token", newAccessToken);
            response.put("expires_in", jwtUtil.getExpiration() / 1000);
            response.put("token_type", "Bearer");

            return ResponseEntity.ok(response);
        } catch (Exception ex) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "invalid_refresh_token");
            return ResponseEntity.status(401).body(errorResponse);
        }
    }
}
